//
//  SNKUserDetailController.m
//  SleepNews
//
//  Created by Kavee DJ on 2017/1/6.
//  Copyright © 2017年 Kavee DJ. All rights reserved.
//

#import "SNKUserDetailController.h"
#import <AVOSCloud.h>
#import <ActionSheetStringPicker.h>
#import <SCLAlertView.h>
#import "SNKResetPasswordController.h"

@interface SNKUserDetailController ()<UINavigationControllerDelegate, UIImagePickerControllerDelegate>

@property (weak, nonatomic) PYCell *cell1;
@property (weak, nonatomic) PYCell *cell3;
@property (weak, nonatomic) UIImageView *headView;

@end

@implementation SNKUserDetailController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"个人信息";
    self.tableView.backgroundColor = [UIColor lightGrayColor];
    
    [self setupCell];
}

#pragma mark - PickerView数据源
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    return 2;
}

#pragma mark - 设置cell
- (void)setupCell {
    
    IMP_BLOCK_SELF(SNKUserDetailController)
    
    UIImage *headImage = nil;
    // 先从沙盒中取图片
    headImage = [UIImage imageWithContentsOfFile:SNKHeadImageLocalPath];
    if (headImage == nil) {
        // 从服务器获取图片
        AVUser *currentUser = [AVUser currentUser];
        AVFile *headImageFile = [currentUser objectForKey:SNKUserHeadImageKey];
        NSData *headImageData = [headImageFile getData];
        headImage = [UIImage imageWithData:headImageData];
        if (headImage == nil) { // 服务器也没有，就是没有设置图片
            headImage = [UIImage imageNamed:@"comment_profile_default"];
        }
    }
    UIImageView *headView = [[UIImageView alloc] initWithImage:headImage];
    headView.bounds = CGRectMake(0, 0, 60, 60);
    self.headView = headView;
    
    PYGroup *group = [[PYGroup alloc] init];
    
    /************************ 头像 ****************************/
    PYCell *cell0 = [PYArrowCell cellWithTitle:@"头像" accessoryView:headView didSelectedCell:^(PYTableViewCell *selectedCell) {
        UIAlertController *userIconAlert = [UIAlertController alertControllerWithTitle:@"设置头像" message:@"😘" preferredStyle:UIAlertControllerStyleActionSheet];
        
        // 从相册选择 Action
        UIAlertAction *chooseFromPhotoAlbum = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [block_self chooseFromPhotoAlbum];
        }];
        [userIconAlert addAction:chooseFromPhotoAlbum];
        
        // 拍照 Action
        UIAlertAction *chooseFromCamera = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [block_self chooseFromCamera];
        }];
        [userIconAlert addAction:chooseFromCamera];
        
        UIAlertAction *canelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
        }];
        [userIconAlert addAction:canelAction];
        
        [block_self presentViewController:userIconAlert animated:YES completion:nil];
    }];
    cell0.selectionStyle = UITableViewCellSelectionStyleNone;
    cell0.height = 70;
    /************************ 头像 ****************************/
    
    
    PYCell *cell1 = [PYArrowCell cellWithTitle:@"昵称" accessoryTitle:[AVUser currentUser].username didSelectedCell:^(PYTableViewCell *selectedCell) {
        
        SCLAlertView *alert = [[SCLAlertView alloc] init];
        UITextField *textField = [alert addTextField:@"请输入昵称"];
        [alert addButton:@"确定" actionBlock:^(void) {
            
            // 更新云端
            [AVUser currentUser].username = textField.text;
            [[AVUser currentUser] saveInBackground];
            
            // 更新table
            block_self.cell1.accessoryTitle = textField.text;
            [block_self.tableView reloadData];
        }];
        [alert showEdit:block_self title:@"更改昵称" subTitle:@"取一个独一无二名字吧" closeButtonTitle:@"取消" duration:0.0f];
    }];
    cell1.selectionStyle = UITableViewCellSelectionStyleNone;
    self.cell1 = cell1;
    
    
    PYCell *cell2 = [PYCell cellWithTitle:@"手机号码" accessoryTitle:[AVUser currentUser].mobilePhoneNumber];
    cell2.selectionStyle = UITableViewCellSelectionStyleNone;
    
    
    
    NSString *userGender = [[AVUser currentUser] objectForKey:@"gender"];
    PYCell *cell3 = [PYArrowCell cellWithTitle:@"性别" accessoryTitle:userGender?userGender:@"请选择" didSelectedCell:^(PYTableViewCell *selectedCell) {
        NSArray *genders = [NSArray arrayWithObjects:@"男", @"女", nil];
        [ActionSheetStringPicker showPickerWithTitle:@"请选择性别" rows:genders initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
            
            [[AVUser currentUser] setObject:(NSString *)selectedValue forKey:@"gender"];
            [[AVUser currentUser] saveInBackground];
            
            block_self.cell3.accessoryTitle = (NSString *)selectedValue;
            [block_self.tableView reloadData];
            
        } cancelBlock:^(ActionSheetStringPicker *picker) {
            
        } origin:block_self.tableView];
    }];
    cell3.selectionStyle = UITableViewCellSelectionStyleNone;
    self.cell3 = cell3;
    
    
    
    PYCell *cell4 = [PYArrowCell cellWithTitle:@"密码设置" accessoryTitle:@"" didSelectedCell:^(PYTableViewCell *selectedCell) {
        SNKResetPasswordController *resetPwdVc = [[SNKResetPasswordController alloc] init];
        [block_self.navigationController pushViewController:resetPwdVc animated:YES];
    }];
    
    PYCell *cell5 = [PYCell cellWithTitle:@"城市" accessoryTitle:[[AVUser currentUser] objectForKey:@"city"]];
    cell5.selectionStyle = UITableViewCellSelectionStyleNone;
    
    group.cells = (NSMutableArray *)@[cell0, cell1, cell2, cell3, cell4, cell5];
    [self.groups addObject:group];
}

#pragma mark - 从相册选择头像
- (void)chooseFromPhotoAlbum {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //获得编辑后的图片
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    //更新头像
    self.headView.image = image;
    
    //保存图片至沙盒
    NSData *imageData = UIImageJPEGRepresentation(image, 0.1);
    [imageData writeToFile:SNKHeadImageLocalPath atomically:YES];
    
    // ------------------更新云端
    // 先删除云端的图片
    AVUser *currentUser = [AVUser currentUser];
    AVFile *preHeadImage = [currentUser objectForKey:SNKUserHeadImageKey];
    [preHeadImage deleteInBackground];
    // 替换为当前图片
    AVFile *curHeadImage = [AVFile fileWithName:SNKHeadImageFullName data:imageData];
    [currentUser setObject:curHeadImage forKey:SNKUserHeadImageKey];
    [currentUser saveInBackground];
    
    [picker dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - 摄像头拍摄
- (void)chooseFromCamera {
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
    [self presentViewController:imagePicker animated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
